<template>
    <div class="oauth2-login-container">
        <el-card class="login-card">
            <template #header>
                <div class="card-header">
                    <h2>登录中...</h2>
                </div>
            </template>
            <div class="loading-container">
                <el-icon class="loading-icon"><Loading /></el-icon>
                <p>正在处理授权登录，请稍候...</p>
            </div>
        </el-card>
    </div>
</template>

<script lang="ts" setup>
import { onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import request from '@/base/request'
import LoginParm from '@/types/user/LoginParm'
import { address } from '@/base/address'
const route = useRoute()
const router = useRouter()

// 处理OAuth2登录
const handleOAuth2Login = async () => {
    try {
        // 获取URL参数
        const code = route.query.code as string
        const backUrl = route.query.backUrl as string
        if (!code || !backUrl) {
            ElMessage.error('缺少必要参数')
            return
        }

        // 获取access token
        const tokenResponse = await request.get(`${address.oauth2Url}/user/oauth2/getTokenByCode`, {
            params: { 
                code,
            }
        })

        if (tokenResponse.data.code !== 200) {
            ElMessage.error(tokenResponse.data.msg || '获取授权令牌失败')
            return
        }

        const accessToken = tokenResponse.data.data

        // 使用access token登录
        const loginParm: LoginParm = {
            type: 'token',
            oauth2AccessToken: accessToken
        }

        const loginResponse = await request.post('/user/userBaseInfo/doLogin', loginParm)

        if (loginResponse.data.code !== 200) {
            ElMessage.error(loginResponse.data.msg || '登录失败')
            return
        }

        // 登录成功，跳转到回调地址
        window.location.href = backUrl
    } catch (error) {
        ElMessage.error('登录处理失败')
        console.error('OAuth2 login error:', error)
    }
}

onMounted(() => {
    handleOAuth2Login()
})
</script>

<style scoped>
.oauth2-login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    background-color: #f5f7fa;
}

.login-card {
    width: 400px;
}

.card-header {
    display: flex;
    justify-content: center;
    align-items: center;
}

.card-header h2 {
    margin: 0;
    font-size: 20px;
    color: #303133;
}

.loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 40px 0;
}

.loading-icon {
    font-size: 40px;
    color: #409eff;
    animation: rotating 2s linear infinite;
}

.loading-container p {
    margin-top: 20px;
    color: #606266;
}

@keyframes rotating {
    from {
        transform: rotate(0deg);
    }
    to {
        transform: rotate(360deg);
    }
}
</style> 